package com.csg.ses.service.ses.impl;

import com.csg.ses.common.utils.CommonUtil;
import com.csg.ses.common.utils.SftpFileUtil;
import lombok.Data;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.sql.Timestamp;
import java.util.Date;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.csg.ses.vo.common.Result;
import com.csg.ses.vo.common.ResultStatus;
import lombok.RequiredArgsConstructor;
import com.csg.ses.common.utils.MybatisPlusUtil;
import com.csg.ses.common.utils.SnowFlakeUtil;
import org.springframework.transaction.annotation.Transactional;
import com.csg.ses.vo.login.UserContext;
import com.csg.ses.vo.login.UserView;
import com.csg.ses.vo.common.IdListVo;
import java.time.LocalDateTime;

import com.csg.ses.dao.ses.FileInfoDao;
import com.csg.ses.entity.ses.FileInfoEntity;
import com.csg.ses.service.ses.FileInfoService;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.Timeable;

import javax.servlet.http.HttpServletResponse;

/**
 * 
 * @author zhanggongrong
 * @date 2021-05-06 17:29:22
 */
@Service
@RequiredArgsConstructor
public class FileInfoServiceImpl extends ServiceImpl<FileInfoDao, FileInfoEntity> implements FileInfoService {
    private final FileInfoDao fileInfoDao;
    private final SftpFileUtil sftpFileUtil;
    private final HttpServletResponse resp;


    @Override
    public Result retrieve(FileInfoEntity fileInfo, Long current, Long size) {
        try {
            Page<FileInfoEntity> page = MybatisPlusUtil.initPage(current, size, true);
            QueryWrapper<FileInfoEntity> qw = new QueryWrapper();
            return new Result(fileInfoDao.retrieve(page, qw), ResultStatus.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

    @Override
    public Result queryAllGroup() {
        return new Result(fileInfoDao.getAllGroup());
    }

    @Override
    @Transactional
    public Result del(IdListVo idList) {
        try {
            if (idList != null && idList.getIdList().size() > 0) {
                int num = fileInfoDao.deleteBatchIds(idList.getIdList());
                return new Result(num + "条记录删除成功！", ResultStatus.SUCCESS);
            } else {
                return new Result("未指定需要删除的记录！", ResultStatus.FAILED);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

    @Override
    public Result getById(String id) {
        if (!CommonUtil.isEmpty(id)) {
            return new Result(fileInfoDao.selectById(id), ResultStatus.SUCCESS);
        } else {
            throw new RuntimeException("id不能为空！");
        }
    }

    @Override
    @Transactional
    public boolean save(FileInfoEntity fileInfo) {
        try {
            if (!CommonUtil.isEmpty(fileInfo.getFileId() + "")) {
                fileInfoDao.updateById(fileInfo);
            } else {
                fileInfo.setFileId(fileInfoDao.getNextId());
                fileInfo.setCreatedTime(new Timestamp(new Date().getTime()));
                fileInfoDao.insert(fileInfo);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

    @Override
    @Transactional
    public boolean uploadFiles(MultipartFile multipartFile, String pathNodeName) throws Exception {
        try {
//            UserView userView = UserContext.getUserView();
            String filename = multipartFile.getOriginalFilename();
//            Long fileSize = multipartFile.getSize();
            String filepath = pathNodeName + "/" + filename;
            System.out.println(filepath);
            //文件上传
            File file = this.multipartFileToFile(multipartFile);
            sftpFileUtil.uploadFile(filepath, new FileInputStream(file));
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }
    /**
     * 将MultipartFile转成File
     * @param multiFile
     * @return
     */
    public File multipartFileToFile(MultipartFile multiFile) {
        String fileName = multiFile.getOriginalFilename();
        String prefix = fileName.substring(fileName.lastIndexOf("."));
        try {
            File file = File.createTempFile(fileName, prefix);
            multiFile.transferTo(file);
            return file;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public void downloadFile(String fileName) throws Exception {
//        System.out.println(fileName);
        String filepath="C:\\Users\\CJJ\\Desktop\\xiTong\\"+fileName;
//        System.out.println(filepath);
        OutputStream output = null;
        OutputStream out = null;
        try {
            File file = new File(filepath);
            output = new FileOutputStream(file, true);
            resp.setHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes("gbk"), "iso-8859-1"));
            out = resp.getOutputStream();
            out.write(CommonUtil.getBytes(filepath));
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        } finally {
            output.close();
            out.close();
        }
    }

}